package org.xiaoweige.mybatis.config;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.stereotype.Component;

/**
 * BeanFactoryHolder
 *
 * @author Jerry.hu
 * @summary BeanFactoryHolder
 * @Copyright (c) 2018, xiaoweige Group All Rights Reserved.
 * @Description BeanFactoryHolder
 * @since 2018-06-09 18:09
 */
@Component
public class BeanFactoryHolder implements BeanFactoryAware {

    private static BeanFactory beanFactory;

    /**
     * 通过name获取 Bean.
     *
     * @param name bean name
     * @return Bean
     */
    public static Object getBean(String name) {
        return beanFactory.getBean(name);
    }

    /**
     * 通过class获取Bean
     */
    public static <T> T getBean(Class<T> clazz) {
        return beanFactory.getBean(clazz);
    }

    /**
     * 通过name,以及Clazz返回指定的Bean
     *
     * @param name  bean 名字
     * @param clazz 类
     * @param <T>   泛型对象
     * @return bean
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        return beanFactory.getBean(name, clazz);
    }

    public static ConversionService getTypeConverter() {
        return DefaultConversionService.getSharedInstance();
    }



    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        if (BeanFactoryHolder.beanFactory == null) {
            BeanFactoryHolder.beanFactory = beanFactory;
        }
        System.out.println("---------------------------------------------------------------------");

        System.out.println("---------------org.xiaoweige.mybatis.config.BeanFactoryHolder------------------------------------------------------");

        System.out.println("========beanFactory配置成功,在普通类可以通过调用SpringUtils.getAppContext()获取beanFactory对象,beanFactory=" + BeanFactoryHolder.beanFactory + "========");

        System.out.println("---------------------------------------------------------------------");
    }
}
